# @rspress/plugin-api-docgen <SourceCode href="https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-api-docgen" />

import { SourceCode } from '@rspress/core/theme';

The plugin is used to generate api document description automatically, powered by [react-docgen-typescript](https://github.com/styleguidist/react-docgen-typescript) and [documentation](https://github.com/documentationjs/documentation).

## Install

import { PackageManagerTabs } from '@theme';

<PackageManagerTabs command="add @rspress/plugin-api-docgen -D" />

## Usage

First of all, you need to add following config:

```ts
// rspress.config.ts
import path from 'path';
import { defineConfig } from '@rspress/core';
import { pluginApiDocgen } from '@rspress/plugin-api-docgen';

export default defineConfig({
  plugins: [
    pluginApiDocgen({
      entries: {
        button: './src/index.ts',
      },
      apiParseTool: 'react-docgen-typescript',
    }),
  ],
});
```

Then you can use API component to inject api documentation to your mdx file:

```mdx
## API

This is API Table

<API moduleName="button" />
```

## Config

The plugin accepts an object, which has the following types:

```ts
interface Options {
  entries?: Record<string, string>;
  apiParseTool?: 'react-docgen-typescript' | 'documentation';
  appDir?: string;
  parseToolOptions?: ParseToolOptions;
}
```

### appDir

`appDir` is used to configure the base directory for parsing，default `process.cwd()`.

### entries

`entries` is used to configure the basic info for parsing.

- key is an identifier that serves as the `moduleName` attribute of the API component.
- value is the relative path to the parsed file.

### apiParseTool

`apiParseTool` is used to choose the tool for parsing，default `react-docgen-typescript`:

- `react-docgen-typescript`is used for component library scenarios, only props will be parsed to generate tables.

```tsx
export type ButtonProps = {
  /**
   * Whether to disable the button
   */
  disabled?: boolean;
  /**
   * Type of Button
   * @default 'default'
   */
  size?: 'mini' | 'small' | 'default' | 'large';
};
export const Button = (props?: ButtonProps) => {};
```

The above is a standard writeup where `ButtonProps` will be extracted into the form and `Button` will be used as the form title.
If you use the default export, the filename will be used as the form title.

Notice that export features declared elsewhere are not available.

```tsx
const A = () => {};

export { A }; // wrong
export default A; // wrong
export const B = () => {}; // right
export default () => {}; // right
```

The generated content is as follows:

```mdx
### ButtonTest

|  Props   |          Description          |                    Type                     |   Default   |
| :------: | :---------------------------: | :-----------------------------------------: | :---------: |
| disabled | Whether to disable the button |                  `boolean`                  |     `-`     |
|   size   |        Type of Button         | `"mini" \| "small" \| "default" \| "large"` | `'default'` |
```

:::warning
If React types are used in Props, you need to add the types in tsconfig.json, otherwise the types will not be resolved under the React namespace.

```json
{
  "compilerOptions": {
    "types": ["react"]
  }
}
```

The best way is that you import the type directly:

```tsx
import { FC } from 'react';
```

:::

- `documentation` is used in tool library scenarios to parse JSDoc annotations.
  Here is a greet function with JSDoc annotations.

```ts
/**
 * Greet function that returns a greeting message.
 * @param {string} name - The name of the person to greet.
 * @param {string} [greeting='Hello'] - The greeting to use.
 * @returns {string} The greeting message.
 */
function greet(name: string, greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}
```

The generated content is as follows:

```md
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## greet

Greet function that returns a greeting message.

### Parameters

- `name` **[string][1]** The name of the person to greet.
- `greeting` **[string][1]** The greeting to use. (optional, default `'Hello'`)

Returns **[string][1]** The greeting message.

[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
```

### parseToolOptions

`parseToolOptions` is used to pass options to the corresponding parse tool, whose types are as follows:

```ts
type ParseToolOptions = {
  'react-docgen-typescript'?: ParserOptions & {
    tsconfigPath?: Record<string, string>;
    compilerOptions?: Record<string, ts.CompilerOptions>;
  };
  documentation?: DocumentationArgs;
};
```

Please refer to [ParserOptions](https://github.com/styleguidist/react-docgen-typescript/blob/b7ea0a235efb7c78a1158ca12d864de2bc2ee30e/src/parser.ts#L84-L95) and [DocumentationArgs](https://github.com/documentationjs/documentation/blob/master/docs/NODE_API.md#parameters-1) to learn about available options.

If the parser is `react-docgen-typescript`, the `withDefaultConfig` method is used by default to create a parser instance. If `tsconfigPath` or `compilerOptions` is configured, `tsconfigPath` and `compilerOptions` can be set separately for each `entry`, the `withCompilerOptions` and `withCustomConfig` methods are used to create the parser instance respectively. See [Custom Parsers](https://github.com/styleguidist/react-docgen-typescript/blob/b7ea0a235efb7c78a1158ca12d864de2bc2ee30e/README.md#usage) for details.
